"""
参数验证工具模块
提供统一的参数验证和错误处理功能
"""

from typing import Any, Dict, List, Optional, Union
from constants import HttpStatus
import re


class ValidationError(Exception):
    """验证错误异常"""
    def __init__(self, message: str, field: str = None, value: Any = None):
        self.message = message
        self.field = field
        self.value = value
        super().__init__(self.message)


class Validator:
    """参数验证器"""
    
    def __init__(self):
        self.errors: List[Dict[str, Any]] = []
    
    def required(self, field: str, value: Any, message: str = None) -> 'Validator':
        """验证必填字段"""
        if value is None or value == "" or (isinstance(value, list) and len(value) == 0):
            self.errors.append({
                "field": field,
                "message": message or f"{field}是必填字段",
                "value": value,
                "rule": "required"
            })
        return self
    
    def string(self, field: str, value: Any, min_length: int = None, max_length: int = None, message: str = None) -> 'Validator':
        """验证字符串"""
        if value is not None:
            if not isinstance(value, str):
                self.errors.append({
                    "field": field,
                    "message": message or f"{field}必须是字符串",
                    "value": value,
                    "rule": "string"
                })
            else:
                if min_length is not None and len(value) < min_length:
                    self.errors.append({
                        "field": field,
                        "message": f"{field}长度不能少于{min_length}个字符",
                        "value": value,
                        "rule": "min_length"
                    })
                if max_length is not None and len(value) > max_length:
                    self.errors.append({
                        "field": field,
                        "message": f"{field}长度不能超过{max_length}个字符",
                        "value": value,
                        "rule": "max_length"
                    })
        return self
    
    def integer(self, field: str, value: Any, min_value: int = None, max_value: int = None, message: str = None) -> 'Validator':
        """验证整数"""
        if value is not None:
            try:
                int_value = int(value)
                if min_value is not None and int_value < min_value:
                    self.errors.append({
                        "field": field,
                        "message": f"{field}不能小于{min_value}",
                        "value": value,
                        "rule": "min_value"
                    })
                if max_value is not None and int_value > max_value:
                    self.errors.append({
                        "field": field,
                        "message": f"{field}不能大于{max_value}",
                        "value": value,
                        "rule": "max_value"
                    })
            except (ValueError, TypeError):
                self.errors.append({
                    "field": field,
                    "message": message or f"{field}必须是整数",
                    "value": value,
                    "rule": "integer"
                })
        return self
    
    def email(self, field: str, value: Any, message: str = None) -> 'Validator':
        """验证邮箱格式"""
        if value is not None and value != "":
            email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            if not re.match(email_pattern, str(value)):
                self.errors.append({
                    "field": field,
                    "message": message or f"{field}格式不正确",
                    "value": value,
                    "rule": "email"
                })
        return self
    
    def has_errors(self) -> bool:
        """检查是否有验证错误"""
        return len(self.errors) > 0
    
    def get_errors(self) -> List[Dict[str, Any]]:
        """获取所有验证错误"""
        return self.errors.copy()


def create_validation_response(errors: List[Dict[str, Any]], received_data: Dict[str, Any] = None) -> Dict[str, Any]:
    """创建验证错误响应"""
    response = {
        "code": HttpStatus.BAD_REQUEST,
        "msg": "参数验证失败",
        "data": None,
        "errors": errors,
        "error_count": len(errors)
    }
    
    # 如果提供了接收到的数据，也返回以便调试
    if received_data:
        response["received_data"] = received_data
    
    return response